<template>
  <div class="feedback-list">
    <el-card class="feedback-card">
      <template #header>
        <div class="card-header">
          <span>意见反馈管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入反馈标题或内容"
              style="width: 300px; margin-right: 10px"
              clearable
              :maxlength="200"
              @clear="handleSearch"
              @keydown.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" :loading="loading" />
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table
        :data="feedbackList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="user.name" label="反馈用户" width="120" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)">
              {{ formatType(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" show-overflow-tooltip />
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="scope">
            <el-tag :type="getPriorityTagType(scope.row.priority)">
              {{ formatPriority(scope.row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="反馈时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button
              size="small"
              type="success"
              @click="handleProcess(scope.row)"
              v-if="scope.row.status === 'PENDING'"
            >
              处理
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleResolve(scope.row)"
              v-if="scope.row.status === 'PROCESSING'"
            >
              解决
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看反馈详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="反馈详情"
      width="800px"
    >
      <div class="feedback-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="用户">{{ currentFeedback.user?.name || '未知用户' }}</el-descriptions-item>
          <el-descriptions-item label="类型">
            <el-tag :type="getTypeTagType(currentFeedback.type)">
              {{ formatType(currentFeedback.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="分类">{{ currentFeedback.category }}</el-descriptions-item>
          <el-descriptions-item label="标题">{{ currentFeedback.title }}</el-descriptions-item>
          <el-descriptions-item label="内容">{{ currentFeedback.content }}</el-descriptions-item>
          <el-descriptions-item label="图片" v-if="currentFeedback.images && currentFeedback.images.length > 0">
            <div class="feedback-images">
              <el-image
                v-for="image in currentFeedback.images"
                :key="image"
                :src="image"
                :preview-src-list="currentFeedback.images"
                :initial-index="currentFeedback.images.indexOf(image)"
                style="width: 100px; height: 100px; margin-right: 10px; margin-bottom: 10px;"
              />
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentFeedback.contactPhone }}</el-descriptions-item>
          <el-descriptions-item label="联系邮箱">{{ currentFeedback.contactEmail }}</el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityTagType(currentFeedback.priority)">
              {{ formatPriority(currentFeedback.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentFeedback.status)">
              {{ formatStatus(currentFeedback.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="回复">{{ currentFeedback.reply }}</el-descriptions-item>
          <el-descriptions-item label="解决时间">{{ currentFeedback.resolvedAt }}</el-descriptions-item>
          <el-descriptions-item label="反馈时间">{{ currentFeedback.createdAt }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 处理反馈对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="处理反馈"
      width="600px"
    >
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="状态" prop="status">
          <el-select v-model="processForm.status" placeholder="请选择处理状态" style="width: 100%">
            <el-option label="处理中" value="PROCESSING" />
            <el-option label="已解决" value="RESOLVED" />
            <el-option label="已关闭" value="CLOSED" />
            <el-option label="已拒绝" value="REJECTED" />
          </el-select>
        </el-form-item>
        <el-form-item label="回复内容" prop="reply">
          <el-input
            v-model="processForm.reply"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
            :maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveProcess" :loading="processLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Feedback } from '@/types/api/review'
import { feedbackApi } from '@/api/modules/review'
import { preventDuplicateSubmit, formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const feedbackList = ref<Feedback[]>([])
const currentFeedback = ref<Feedback>({
  id: 0,
  userId: 0,
  type: 'SUGGESTION',
  title: '',
  content: '',
  images: [],
  priority: 'NORMAL',
  status: 'PENDING',
  createdAt: ''
})

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const detailDialogVisible = ref(false)
const processDialogVisible = ref(false)
const processLoading = ref(false)
const processFormRef = ref()
const currentFeedbackId = ref(0)

// 处理表单数据
const processForm = reactive({
  status: 'PROCESSING' as 'PROCESSING' | 'RESOLVED' | 'CLOSED' | 'REJECTED',
  reply: ''
})

// 表单验证规则
const processRules = {
  status: [
    { required: true, message: '请选择处理状态', trigger: 'change' }
  ],
  reply: [
    { required: true, message: '请输入回复内容', trigger: 'blur' }
  ]
}

// 获取反馈列表
const getFeedbackList = async () => {
  try {
    loading.value = true
    const response = await feedbackApi.getAllFeedbackList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword
    })
    feedbackList.value = response.data.data.list
    pagination.total = response.data.data.total
  } catch (error) {
    ElMessage.error('获取反馈列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getFeedbackList()
}

// 刷新列表
const refreshList = () => {
  getFeedbackList()
}

// 查看反馈详情
const handleView = (row: Feedback) => {
  currentFeedback.value = row
  detailDialogVisible.value = true
}

// 处理反馈
const handleProcess = async (row: Feedback) => {
  formUtils.handleDeleteConfirm(`反馈 "${row.title}"`, async () => {
    currentFeedbackId.value = row.id
    processForm.status = 'PROCESSING'
    processForm.reply = ''
    processDialogVisible.value = true
  }, {
    title: '处理反馈',
    successMessage: '操作成功',
    errorMessage: '操作失败'
  })
}

// 解决反馈
const handleResolve = async (row: Feedback) => {
  formUtils.handleDeleteConfirm(`反馈 "${row.title}"`, async () => {
    currentFeedbackId.value = row.id
    processForm.status = 'RESOLVED'
    processForm.reply = ''
    processDialogVisible.value = true
  }, {
    title: '解决反馈',
    successMessage: '操作成功',
    errorMessage: '操作失败'
  })
}

// 保存处理结果
const handleSaveProcess = async () => {
  if (!processFormRef.value) return

  try {
    await processFormRef.value.validate()

    // 使用防重复提交保护
    await preventDuplicateSubmit(`process_feedback_${currentFeedbackId.value}`, async () => {
      processLoading.value = true
      try {
        await feedbackApi.handleFeedback(currentFeedbackId.value, {
          status: processForm.status,
          reply: processForm.reply
        })

        ElMessage.success('处理成功')
        processDialogVisible.value = false
        refreshList()
      } catch (error: any) {
        ElMessage.error('处理失败')
        throw error // 重新抛出错误以确保防重复提交正确处理
      } finally {
        processLoading.value = false
      }
    })
  } catch (error: any) {
    // 防重复提交保护捕获的错误
    if (error.message === '请勿重复提交') {
      ElMessage.warning('请勿重复提交')
    }
  }
}

// 分页相关方法
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  getFeedbackList()
}

const handleCurrentChange = (val: number) => {
  pagination.page = val
  getFeedbackList()
}

// 格式化类型
const formatType = (type: string) => {
  const typeMap: Record<string, string> = {
    'BUG': 'BUG',
    'FEATURE': '功能建议',
    'COMPLAINT': '投诉',
    'SUGGESTION': '建议',
    'OTHER': '其他'
  }
  return typeMap[type] || type
}

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    'BUG': 'danger',
    'FEATURE': 'success',
    'COMPLAINT': 'warning',
    'SUGGESTION': '',
    'OTHER': 'info'
  }
  return typeMap[type] || 'info'
}

// 格式化优先级
const formatPriority = (priority: string) => {
  const priorityMap: Record<string, string> = {
    'LOW': '低',
    'NORMAL': '普通',
    'HIGH': '高',
    'URGENT': '紧急'
  }
  return priorityMap[priority] || priority
}

// 获取优先级标签类型
const getPriorityTagType = (priority: string) => {
  const priorityMap: Record<string, string> = {
    'LOW': 'info',
    'NORMAL': '',
    'HIGH': 'warning',
    'URGENT': 'danger'
  }
  return priorityMap[priority] || 'info'
}

// 格式化状态
const formatStatus = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '待处理',
    'PROCESSING': '处理中',
    'RESOLVED': '已解决',
    'CLOSED': '已关闭',
    'REJECTED': '已拒绝'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': 'warning',
    'PROCESSING': '',
    'RESOLVED': 'success',
    'CLOSED': 'info',
    'REJECTED': 'danger'
  }
  return statusMap[status] || 'info'
}

// 生命周期
onMounted(() => {
  getFeedbackList()
})
</script>

<style scoped>
.feedback-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.feedback-images {
  display: flex;
  flex-wrap: wrap;
}
</style>
